package com.agileboot.domain.system.danger;

import com.agileboot.common.core.page.PageDTO;
import com.agileboot.domain.common.command.BulkOperationCommand;

import com.agileboot.domain.system.danger.command.AddDangerSourceCommand;
import com.agileboot.domain.system.danger.command.UpdateDangerSourceCommand;
import com.agileboot.domain.system.danger.db.DangerSourceEntity;
import com.agileboot.domain.system.danger.db.DangerSourceService;
import com.agileboot.domain.system.danger.dto.DangerSourceDTO;
import com.agileboot.domain.system.danger.model.DangerSourceModel;
import com.agileboot.domain.system.danger.model.DangerSourceModelFactory;
import com.agileboot.domain.system.danger.query.DangerSourceQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 危险源应用服务
 * @author [your-name]
 */
@Service
@RequiredArgsConstructor
public class DangerSourceApplicationService {

    private final DangerSourceService dangerSourceService;

    private final DangerSourceModelFactory modelFactory;

    public PageDTO<DangerSourceDTO> getDangerSourceList(DangerSourceQuery query) {
        Page<DangerSourceEntity> page = dangerSourceService.page(query.toPage(), query.toQueryWrapper());
        List<DangerSourceDTO> records = page.getRecords().stream().map(DangerSourceDTO::new).collect(Collectors.toList());
        return new PageDTO<>(records, page.getTotal());
    }

    /**
     * 查询满足条件的所有危险源，不分页
     */
    public List<DangerSourceDTO> getDangerSourceListAll(DangerSourceQuery query) {
        List<DangerSourceEntity> all = dangerSourceService.list(query.toQueryWrapper());
        return all.stream().map(DangerSourceDTO::new).collect(Collectors.toList());
    }

    public DangerSourceDTO getDangerSourceInfo(Long dangerSourceId) {
        DangerSourceEntity entity = dangerSourceService.getById(dangerSourceId);
        return new DangerSourceDTO(entity);
    }

    public void addDangerSource(AddDangerSourceCommand command) {
        DangerSourceModel model = modelFactory.create();
        model.loadFromAddCommand(command);

        model.checkNameUnique();

        dangerSourceService.save(model);
    }

    public void updateDangerSource(UpdateDangerSourceCommand command) {
        DangerSourceModel model = modelFactory.loadById(command.getDangerSourceId());
        model.loadFromUpdateCommand(command);

        model.checkNameUnique();

        dangerSourceService.updateById(model);
    }

    public void deleteDangerSource(BulkOperationCommand<Long> deleteCommand) {
        dangerSourceService.removeBatchByIds(deleteCommand.getIds());
    }
}
